<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="店铺名称" prop="shopName">
        <el-input
            v-model="queryParams.shopName"
            placeholder="请输入店铺名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="提现金额" prop="withdrawAmount">
        <el-input
            v-model="queryParams.withdrawAmount"
            placeholder="请输入提现金额"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="提交时间" prop="submitTime">
        <el-date-picker clearable
                        v-model="queryParams.submitTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择提交时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="处理时间" prop="processTime">
        <el-date-picker clearable
                        v-model="queryParams.processTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择处理时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['order:shopwithdraw:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['order:shopwithdraw:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['order:shopwithdraw:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['order:shopwithdraw:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="shopwithdrawList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="主键" align="center" prop="id" />-->
      <el-table-column label="店铺名称" align="center" prop="shopName" />
      <el-table-column label="提现金额" align="center" prop="withdrawAmount" />
      <el-table-column label="实际到账金额" align="center" prop="actualAmount" />
      <el-table-column label="平台服务费" align="center" prop="platformFee" />
      <el-table-column label="提现状态" align="center" prop="status">
        <template #default="{ row }">
          <el-tag :type="statusType(row.status)" effect="light" size="small">
            {{ statusLabel(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审核不通过原因" align="center" prop="rejectReason" />
      <el-table-column label="提交时间" align="center" prop="submitTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.submitTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="处理时间" align="center" prop="processTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.processTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Check" @click="openAudit(scope.row)" v-hasPermi="['order:shopwithdraw:edit']">审核</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['order:shopwithdraw:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 审核弹窗 -->
    <el-dialog title="提现审核" v-model="auditOpen" width="480px" append-to-body>
      <el-form ref="auditRef" :model="auditForm" :rules="auditRules" label-width="90px">
        <el-form-item label="审核结果" prop="decision">
          <el-radio-group v-model="auditForm.decision">
            <el-radio label="PASS">审核通过</el-radio>
            <el-radio label="REJECT">审核拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="拒绝原因" prop="rejectReason" v-if="auditForm.decision === 'REJECT'">
          <el-input v-model="auditForm.rejectReason" placeholder="请输入拒绝原因" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="auditOpen=false">取 消</el-button>
          <el-button type="primary" @click="submitAudit">提 交</el-button>
        </div>
      </template>
    </el-dialog>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改商家提现记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="shopwithdrawRef" :model="form" :rules="rules" >
        <el-form-item label="店铺名称" prop="shopName">
          <el-input v-model="form.shopName" placeholder="请输入店铺名称" />
        </el-form-item>
        <el-form-item label="提现金额" prop="withdrawAmount">
          <el-input v-model="form.withdrawAmount" placeholder="请输入提现金额" />
        </el-form-item>
        <el-form-item label="实际到账金额" prop="actualAmount">
          <el-input v-model="form.actualAmount" placeholder="请输入实际到账金额" />
        </el-form-item>
        <el-form-item label="平台服务费" prop="platformFee">
          <el-input v-model="form.platformFee" placeholder="请输入平台服务费" />
        </el-form-item>
        <el-form-item label="审核不通过原因" prop="rejectReason">
          <el-input v-model="form.rejectReason" placeholder="请输入审核不通过原因" />
        </el-form-item>
        <el-form-item label="提交时间" prop="submitTime">
          <el-date-picker clearable
                          v-model="form.submitTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择提交时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="处理时间" prop="processTime">
          <el-date-picker clearable
                          v-model="form.processTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择处理时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Shopwithdraw">
import { listShopwithdraw, getShopwithdraw, delShopwithdraw, addShopwithdraw, updateShopwithdraw } from "@/api/order/shopwithdraw"

const { proxy } = getCurrentInstance()

const shopwithdrawList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    shopName: null,
    withdrawAmount: null,
    actualAmount: null,
    platformFee: null,
    status: null,
    rejectReason: null,
    submitTime: null,
    processTime: null
  },
  rules: {
    shopName: [
      { required: true, message: "店铺名称不能为空", trigger: "blur" }
    ],
    withdrawAmount: [
      { required: true, message: "提现金额不能为空", trigger: "blur" }
    ],
    actualAmount: [
      { required: true, message: "实际到账金额不能为空", trigger: "blur" }
    ],
    platformFee: [
      { required: true, message: "平台服务费不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "提现状态不能为空", trigger: "change" }
    ],
    submitTime: [
      { required: true, message: "提交时间不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询商家提现记录列表 */
function getList() {
  loading.value = true
  listShopwithdraw(queryParams.value).then(response => {
    shopwithdrawList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 审核弹窗状态（JS版）
const auditOpen = ref(false)
const auditForm = reactive({
  id: null,
  decision: 'PASS', // PASS | REJECT
  rejectReason: ''
})

const auditRules = {
  decision: [{ required: true, message: '请选择审核结果', trigger: 'change' }],
  rejectReason: [
    {
      validator: (rule, value, callback) => {
        if (auditForm.decision === 'REJECT' && (!value || !String(value).trim())) {
          return callback(new Error('请输入拒绝原因'))
        }
        callback()
      },
      trigger: 'blur'
    }
  ]
}

// 打开审核弹窗
function openAudit(row) {
  auditForm.id = row.id
  auditForm.decision = 'PASS'
  auditForm.rejectReason = ''
  auditOpen.value = true
}

// 提交审核
function submitAudit() {
  proxy.$refs.auditRef.validate(valid => {
    if (!valid) return
    const statusText = auditForm.decision === 'PASS' ? '到账成功' : '审核不通过'
    // 本地 YYYY-MM-DD
    const d = new Date()
    const today = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`

    const payload = {
      id: auditForm.id,
      status: statusText,
      processTime: today,
      rejectReason: auditForm.decision === 'REJECT' ? auditForm.rejectReason : null
    }

    updateShopwithdraw(payload).then(() => {
      proxy.$modal.msgSuccess('审核提交成功')
      auditOpen.value = false
      getList()
    })
  })
}

// 若后端直接返回中文枚举
const STATUS_MAP = {
  '待审核':     { label: '待审核',     type: 'warning' },
  '到账成功':   { label: '到账成功',   type: 'success' },
  '审核不通过': { label: '审核不通过', type: 'danger' }
}

const statusType = (s) => (STATUS_MAP[s]?.type) || 'info'
const statusLabel = (s) => (STATUS_MAP[s]?.label) || s

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    shopName: null,
    withdrawAmount: null,
    actualAmount: null,
    platformFee: null,
    status: null,
    rejectReason: null,
    submitTime: null,
    processTime: null
  }
  proxy.resetForm("shopwithdrawRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加商家提现记录"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getShopwithdraw(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改商家提现记录"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["shopwithdrawRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateShopwithdraw(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addShopwithdraw(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除商家提现记录编号为"' + _ids + '"的数据项？').then(function() {
    return delShopwithdraw(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('order/shopwithdraw/export', {
    ...queryParams.value
  }, `shopwithdraw_${new Date().getTime()}.xlsx`)
}

getList()
</script>
